package two.chapter_1.c1_3;

import java.util.Iterator;

public class ResizingArrayStack<Item> extends Stack<Item> {

    private Item[] items;
    private static final int DEFAULT_CAPACITY=10;
    private int size;
    public ResizingArrayStack(){
        items= (Item[]) new Object[DEFAULT_CAPACITY];
    }

    public void push(Item item){
        ensureCapacity();
        items[size++]=item;
    }

    private void ensureCapacity() {
        if (items.length==size){
            resize(2*size);
        }
    }

    private void resize(int newLength) {
        Item[] newItems= (Item[]) new Object[newLength];
        System.arraycopy(items,0,newItems,0,newLength);
        items=newItems;
    }

    public Item pop(){

        Item item=items[--size];
        if (size>0&&size*4<items.length){
            resize(items.length/2);
        }
        items[size]=null;//避免对象游离
        return item;
    }

    @Override
    public Item peek() {
        return null;
    }

    @Override
    public boolean isEmpty() {
        return size()==0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator<Item> iterator() {
        return new Iter();
    }

    private class Iter implements Iterator<Item>{

        private int position;
        public Iter(){
            position=size-1;
        }
        @Override
        public boolean hasNext() {
            return position>=0;
        }

        @Override
        public Item next() {
            return items[position--];
        }

        @Override
        public void remove() {

        }
    }
}
